package com.foeye.bean;

import java.io.Serializable;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class HibernateDaoUtil {

	Session s = null;

	/****************** Add Object ******************/
	public void addObj(Object entity) {
		Transaction tx = null;
		try {
			s = HibernateSessionFactory.getSession();
			tx = s.beginTransaction();
			s.save(entity);
			tx.commit();
			System.out.println("add success!");
		} catch (HibernateException ex) {
			if (tx != null) {
				tx.rollback();
			}
			ex.printStackTrace();
		} finally {
			HibernateSessionFactory.closeSession();
		}
	}

	/****************** Update Object ******************/
	public void updateObj(Object entity) {
		Transaction tx = null;
		try {
			s = HibernateSessionFactory.getSession();
			tx = s.beginTransaction();
			s.update(entity);
			tx.commit();
			System.out.println("update success!");
		} catch (HibernateException ex) {
			if (tx != null) {
				tx.rollback();
			}
			ex.printStackTrace();
		} finally {
			HibernateSessionFactory.closeSession();
		}
	}

	/****************** Delete Object ******************/
	public void deleteObj(Object entity) {
		Transaction tx = null;
		try {
			s = HibernateSessionFactory.getSession();
			tx = s.beginTransaction();
			s.delete(entity);
			tx.commit();
			System.out.println("Delete success!");
		} catch (HibernateException ex) {
			if (tx != null) {
				tx.rollback();
			}
			ex.printStackTrace();
		} finally {
			HibernateSessionFactory.closeSession();
		}
	}

	/******************* QueryObjectById *********************/
	public Object getObject(Class clazz, Serializable id) {
		Object obj = null;
		try {
			s = HibernateSessionFactory.getSession();
			obj = s.get(clazz, id);
		} catch (HibernateException ex) {
			ex.printStackTrace();
		} finally {
			HibernateSessionFactory.closeSession();
		}
		return obj;
	}

}
